package com.icarus.quartz.service.impl;

import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.icarus.quartz.constant.QuartzJobConstant;
import com.icarus.quartz.entity.QuartzJob;
import com.icarus.quartz.job.IQuartzJobBaseService;
import com.icarus.quartz.mapper.QuartzJobMapper;
import com.icarus.quartz.service.QuartzJobService;
import com.icarus.quartz.service.QuartzManager;
import com.icarus.util.SpringUtil;

@Service(value = "quartzJobService")
public class QuartzJobServiceImp implements QuartzJobService {

	@Autowired
	public QuartzJobMapper quartzJobMapper;

	@Autowired
	public QuartzManager quartzManager;

	@Override
	@Transactional(propagation = Propagation.REQUIRED)
	public int add(QuartzJob quartzJob) throws Exception {
		return quartzJobMapper.insert(quartzJob);
	}

	@Override
	@Transactional(readOnly = true)
	public List<QuartzJob> getList() throws Exception {
		return quartzJobMapper.selectByExample(null);
	}

	@Override
	@Transactional(propagation = Propagation.REQUIRED)
	public void init() throws Exception {
		List<String> curBeans = quartzJobMapper.findCurJobBean();
		
		Map<String, IQuartzJobBaseService> map = SpringUtil
				.getBeansByType(IQuartzJobBaseService.class);
		Set<Entry<String, IQuartzJobBaseService>> set = map.entrySet();
		Iterator<Entry<String, IQuartzJobBaseService>> it = set.iterator();
		while (it.hasNext()) {
			Entry<String, IQuartzJobBaseService> entry = it.next();
			String beanName = entry.getKey();
			if (curBeans.contains(beanName)) {
				continue;
			}
			IQuartzJobBaseService jobService = entry.getValue();
			com.icarus.quartz.annotation.QuartzJob jobAnnotation = jobService
					.getClass().getAnnotation(
							com.icarus.quartz.annotation.QuartzJob.class);
			QuartzJob job = new QuartzJob();
			job.setJobId(beanName);
			job.setJobBeanName(beanName);
			job.setJobName(jobAnnotation.name());
			job.setCronExpression(jobAnnotation.cron());
			job.setJobGroup(jobAnnotation.group());
			job.setJobBeanName(beanName);
			job.setJobStatus(QuartzJobConstant.ENABLED);
			add(job);
			quartzManager.add(job);
		}

	}

}
